package com.nakamachizu.controller;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Logger;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;
import org.slim3.util.StringUtil;
import org.slim3.util.TimeZoneLocator;

import com.google.appengine.api.datastore.Text;
import com.nakamachizu.constant.AppConstant;
import com.nakamachizu.model.ContactMailData;
import com.nakamachizu.util.ErrorsUtil;
import com.nakamachizu.util.ForwardUtil;
import com.nakamachizu.util.MailUtil;
import com.nakamachizu.util.PocketCloudStringUtil;
import com.nakamachizu.util.TokenCheck;

public class ContactController extends Controller {

    private static final Logger log = Logger.getLogger(ContactController.class.getName());
    
    private String cmd_confirm;
    private String cmd_send;
    private String subject;
    private String body;
    private String mailAddress;
    private List<String>messages;
    
    @Override
    public Navigation run() throws Exception{
        
        init();
        
        if(validate()){
        
            if(!StringUtil.isEmpty(cmd_confirm)){
                
                TokenCheck.saveToken(request);
                
                return forward(ForwardUtil.forwardJsp("contact_confirm.jsp"));
            
            }else if(!StringUtil.isEmpty(cmd_send)){
                
                if(TokenCheck.validate(request)){
                    List<String>toAddress = new ArrayList<String>();
                    // お問い合わせ番号
                    String contactNo = RandomStringUtils.randomNumeric(8);
                    
                    StringBuffer buf = new StringBuffer(body);
                    StringBuffer headerBuf = new StringBuffer();
                    buf.append("\n---------------\n");
                    buf.append("contactNo: ").append(contactNo).append("\n");
                    buf.append("RemoteAddress: ").append(request.getRemoteAddr()).append("\n");
                    headerBuf.append("RemoteAddress: ").append(request.getRemoteAddr()).append("\n");
                    List<String>headers = PocketCloudStringUtil.getHttpHeaders(request);
                    for(String header : headers){
                        buf.append(header).append("\n");
                        headerBuf.append(header).append("\n");
                    }

                    Text bodyText = new Text(body);
                    Text header = new Text(headerBuf.toString());
                    
                    ContactMailData data = new ContactMailData();
                    data.setSubject(subject);
                    data.setBody(bodyText);
                    data.setHeader(header);
                    data.setMailAddress(mailAddress);
                    data.setContactNo(contactNo);
                    data.setEntryDate(Calendar.getInstance(TimeZoneLocator.get()).getTime());
                    Datastore.put(data);
                    
                    // サポートへメール送信
                    MailUtil util = new MailUtil();
                    toAddress.add(AppConstant.ADMIN_MAIL_ADDRESS());
                    util.send(toAddress, AppConstant.ADMIN_MAIL_ADDRESS(), subject, buf.toString(), null);
                    
                    // 自動返信メール
                    toAddress = new ArrayList<String>();
                    toAddress.add(mailAddress);
                    String autoMailBody = makeAutoMailBody(contactNo, AppConstant.ADMIN_MAIL_ADDRESS());
                    List<String>bcc = new ArrayList<String>();
                    bcc.add(AppConstant.ADMIN_MAIL_ADDRESS());
                    util.sendBcc(toAddress, AppConstant.ADMIN_MAIL_ADDRESS(), bcc, "お問い合わせありがとうございます", autoMailBody, null);
                    
                    requestScope("contactNo", contactNo);
                    
                    return forward(ForwardUtil.forwardJsp("contact_end.jsp"));
                }else{
                    ErrorsUtil.putErrors(errors, request, "message.error.token", "token_error");
                }
            }
            
        }
        
        return forward(ForwardUtil.forwardJsp("contact.jsp"));
    }
    
    protected void init(){
        cmd_confirm = requestScope("cmd_confirm");
        cmd_send = requestScope("cmd_send");
        subject = requestScope("subject");
        body = requestScope("body");
        mailAddress = requestScope("mailAddress");
        messages = new ArrayList<String>();
    }
    
    protected boolean validate() {
        boolean result = true;
        Validators v = new Validators(request);
        if(!StringUtil.isEmpty(cmd_send) || !StringUtil.isEmpty(cmd_confirm)){
            v.add("subject", v.required());
            v.add("body", v.required());
            v.add("mailAddress", v.required());
            if(!StringUtil.isEmpty(mailAddress)){
                if(!MailUtil.isValidMailAddress(mailAddress)){
                    ErrorsUtil.putErrors(errors, request, "message.error.mailaddress", "mailAddress", mailAddress);
                }
            }
            if(!StringUtil.isEmpty(subject)){
                v.add("subject", v.maxlength(30));
            }
            if(!StringUtil.isEmpty(body)){
                v.add("body", v.maxlength(1000));
            }
            result = v.validate();
        }

        return result;
    }
    
    @Override
    protected Navigation handleError(Throwable error) {
        error.printStackTrace();
        log.severe(ErrorsUtil.stackTrace(error));
        return forward("error.jsp");
    }
    
    protected String makeAutoMailBody(String contactNo, String adminMailAddress) throws Exception{
        String result = "";
        
        Velocity.init("WEB-INF/velocity_conf.properties");
        VelocityContext context = new VelocityContext();

        context.put("contactNo", contactNo);
        context.put("adminMailAddress", adminMailAddress);

        StringWriter sw = new StringWriter();
        Template template = Velocity.getTemplate("contact.tmpl", "UTF-8");
        template.merge(context, sw);
        result = sw.toString();
        sw.flush();

        return result;
    }
    
}
